﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PBOffice.DAL;

namespace PBOffice.BLL
{
	public class PluginsManager : IDisposable
	{
		MyOfficeEntities db = new MyOfficeEntities();

		/// <summary>
		/// 获取用户的桌面插件列表
		/// </summary>
		/// <param name="user"></param>
		/// <returns></returns>
		public List<Plugin> GetPlugins(User user)
		{
			var userPlugin = (from up in db.UserPlugins
							  where up.UP_UserNo == user.UserNo
							  select up).SingleOrDefault();
			if (userPlugin == null) //该用户桌面插件记录还不存在，创建之
			{
				var getIDs = from p in db.Plugins
							 select p.P_ID;
				var userP = UserPlugin.CreateUserPlugin(user.UserNo);
				userP.UP_Plugins = string.Join(",", getIDs);
				db.UserPlugins.AddObject(userP);
				db.SaveChanges();
				userPlugin = userP;
			}
			List<Plugin> plugins = new List<Plugin>();
			var IDs = userPlugin.UP_Plugins.Split(',');
			foreach (var id in IDs)
			{
				int pid = 0;
				if (!int.TryParse(id, out pid)) continue;
				var plugin = db.Plugins.SingleOrDefault(p => p.P_ID == pid);
				if (plugin != null)
					plugins.Add(plugin);
			}
			return plugins;
		}

		/// <summary>
		/// 保存桌面状态
		/// </summary>
		/// <param name="user"></param>
		/// <param name="IDs"></param>
		public void SaveDesktop(User user, string IDs) 
		{
			var userPlugin = (from u in db.UserPlugins
							  where u.UP_UserNo == user.UserNo
							  select u).SingleOrDefault();
			if (userPlugin != null)
			{
				userPlugin.UP_Plugins = IDs;
				db.SaveChanges();
			}
		}

		/// <summary>
		/// 重置桌面
		/// </summary>
		/// <param name="userno"></param>
		public void ResetDesktop(User user)
		{
			var userPlugin = (from u in db.UserPlugins
							  where u.UP_UserNo == user.UserNo
							  select u).SingleOrDefault();
			if (userPlugin != null)
			{
				var getIDs = from p in db.Plugins
							 select p.P_ID;
				userPlugin.UP_Plugins = string.Join(",", getIDs);
				db.SaveChanges();
			}
		}

		public void Dispose()
		{
			db.Dispose();
		}
	}
}
